/*
 * Copyright (c) htwang-hpu
 */

package chapt2.exer;

import java.util.Scanner;


public class PrintCalendar {

	/**
	 * @param args
	 */
	public static void printMonth(int y, int m){
		
		printMonthTitle(y, m);
		
		int weekDay = getStartDay(y, m);
		
		int days = getNumberOfDaysInMonth(y, m);
		
		int i,j;
		
		for(i = 0; i < weekDay; i++)
			System.out.print("    ");
		
		for(j = 1; j <= days; j++){
			System.out.printf("%4d",j);
			if((j + weekDay) % 7 == 0)
				System.out.println();
		}		
	}
	
	
	public static void printMonthTitle(int y, int m){
		
		System.out.printf("\t%4s\t%5d\n", printMonthName(m), y);
		
		System.out.println("--------------------------------");
		
		System.out.println("  Sun Mon Tue Wed Thu Fri Sat");
		
	}
//修改并保持	
	public static String printMonthName(int m){
		String name = "";

		if(m==1)
			name = "January";
		else if(m == 2)
			name = "February";
		else if(m == 3)
			name = "March";
		else if(m == 4)
			name = "April";
		else if(m == 5)
			name = "May";
		else if(m == 6)
			name = "June";
		else if(m == 7)
			name = "July";
		else if(m == 8)
			name = "August";
		else if(m == 9)
			name = "September";
		else if(m == 10)
			name = "October";
		else if(m == 11)
			name = "November";
		else 
			name = "December";		
		return name;	
	}
	
	//week day of every month beginning 
	// As we all known that the first day of 1800 is wed
	public static int getStartDay(int year, int month){	
						
		final int WEEK_DAY_START_OF_YEAR = 3;
		return (getTotalNumberOfDays(year, month) + WEEK_DAY_START_OF_YEAR)%7;
	}
	
	public static int getTotalNumberOfDays(int year, int month){
		
		final int  START_OF_YEAR = 1800;
		int totalDays = 0;
		int i, j;
		for(i = START_OF_YEAR; i < year; i++){
			if (isLeapYear(i))
				totalDays +=366;
			else
				totalDays +=365;
		}
		
		for(j = 1; j <month; j++)
			totalDays += getNumberOfDaysInMonth(year, j);
		
		return totalDays;
	}
	
	
	public static int getNumberOfDaysInMonth(int year, int month){
		
		int days;
		
		if(month == 1 || month == 3 || month == 5 || month == 7
				|| month == 8 || month == 10 || month == 12)
			days = 31;
		else if(month == 4 || month == 6 || month == 9 || month == 11 )
			days = 30;
		else if (month == 2 && isLeapYear(year))
			days = 29;
		else 
			days = 28;
		
		return days;
	}
	
	
	
	//test whether year is leap or not
	public static boolean isLeapYear(int year){
		
		boolean flag = false;
		if((year % 400 == 0 )|| (year % 100 != 0 && year % 4 == 0))
			flag = true;
		
		return flag;
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		
		Scanner in = new Scanner(System.in);
		
		System.out.println("Please enter year (e.g.,2001):");
		
		int year = in.nextInt();
		
		System.out.println("Please enter month (e.g.,1-12):");
		
		int month = in.nextInt();
		
		printMonth(year,month);

	}

}
